package com.tansty.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.tansty.common.utils.CommonUtil;
import com.tansty.pojo.dto.PetDTO;
import com.tansty.pojo.po.Category;
import com.tansty.pojo.po.Pet;
import com.tansty.pojo.vo.ResultVO;
import com.tansty.service.service.CategoryService;
import com.tansty.service.service.PetService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * description:  <br>
 * date: 2021/8/25 18:51 <br>
 * author: ztz <br>
 * version: 1.0 <br>
 */
@RestController
@RequestMapping("/pet")
public class PetController {
    @Autowired
    PetService petService;
    @Autowired
    CategoryService categoryService;

    @GetMapping("/all")
    public ResultVO getAll(){
       return CommonUtil.ajaxReturn( petService.getAll());
    }
    @PreAuthorize("hasRole('ADMIN')")
    @PutMapping({"/update", "/add"})
    public ResultVO updatePet(@RequestBody PetDTO petDTO){
        if("售出".equals(petDTO.getIsBuyText())){
            petDTO.setIsBuy(1);
        }else if("未售出".equals(petDTO.getIsBuyText())){
            petDTO.setIsBuy(0);
        }else{
            return new ResultVO("参数错误",400,"售卖情况传输不合法");
        }
        Category name = categoryService.getOne(new QueryWrapper<Category>().eq("name", petDTO.getCategoryName()));
        if(name==null){
            categoryService.save(new Category().setName(petDTO.getName()));
        }
        Pet pet = new Pet();
        pet.setCategoryId(name.getId());
        BeanUtils.copyProperties(petDTO,pet);
        return CommonUtil.ajaxReturn(petService.saveOrUpdate(pet));
    }
    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/delete")
    public ResultVO deletePet(@RequestBody PetDTO petDTO){
        return CommonUtil.ajaxReturn(petService.removeById(petDTO.getId()));
    }


}
